package com.jiu345.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import java.io.InputStream;

/**
 * package:AliOSSUtil
 * Date: 2024.03.12 21:40
 * author:Mr Lei
 * desc:阿里云OSS
 * 参考视频：
 * https://www.bilibili.com/video/BV14z4y1N7pg/?p=37&spm_id_from=333.880.my_history.page.click&vd_source=7e22314a0fb6f43a7a12a417d6d39d05
 */
public class AliOssUtil {
    private static final String ENDPOINT = "https://oss-cn-chengdu.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAI5tKMhST1ukdtMfyNpDcM";
    private static final String ACCESS_KEY_SECRET = "3R2L8vTJLU9QzRbLC1CfKttlLPCi3M";
    public static final String BUCKET_NAME = "jiu345"; //Bucket名称

    public static String uploadFile(String objectName, InputStream in) throws Exception {
        String url = "";

        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
//        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称，例如examplebucket。


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            ossClient.putObject(BUCKET_NAME, objectName, in);

            url = "https://" + BUCKET_NAME + "." + "oss-cn-chengdu.aliyuncs.com/" + objectName;
            // 关闭OSSClient。
            ossClient.shutdown();
        } catch (Exception oe) {
            System.out.println("Error occurred: " + oe.getMessage());
        }
            return url;
    }
}

